package com.chinastock.listener;

import com.chinastock.Constant;
import com.chinastock.log.LogName;
import com.chinastock.model.EcpMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * @author zhangfan.it
 * @date 2021/2/9
 */
@Component
public class EnvListener implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger logger = LoggerFactory.getLogger(LogName.ROOT);
    private static final Logger ecpLog = LoggerFactory.getLogger(LogName.ECP);
    private static final String SERVICE_NAME = "serviceName";
    private static final String PROP_SERVICE_NAME = "spring.application.name";
    private static final String DEFAULT = "NAN";
    private static final String PROP_SYS_NAME = "sys.name";
    private static final String SYS_NAME = "systemName";

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String address = null;
        try {
            address = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            ecpLog.error((new EcpMessage(e)).toString());
        }
        if (address != null) {
            System.setProperty(Constant.SERVER_IP, address);
        } else {
            System.setProperty(Constant.SERVER_IP, Constant.DEFAUT_IP);
            logger.warn("no service ip in env");
        }

        Environment env = event.getApplicationContext().getEnvironment();
        String appName = env.getProperty(PROP_SERVICE_NAME);
        if (appName != null) {
            System.setProperty(SERVICE_NAME, appName);

        } else {
            System.setProperty(SERVICE_NAME, DEFAULT);
            logger.warn("no spring.application.name in env");
        }

        String sysName = env.getProperty(PROP_SYS_NAME);
        if (sysName != null) {
            System.setProperty(SYS_NAME, sysName);
        } else {
            System.setProperty(SYS_NAME, DEFAULT);
            logger.warn("no sys.name in env");
        }
    }
}
